from datetime import datetime
import time

from flask import current_app
from flask import g, jsonify
from flask import request

from info import db
from info.libs.qiuniu import image_storage
from info.models import House, Area, Facility, HouseImage
from info.utils.common import pro_blue
from . import house_blue
@house_blue.route('/api/v1.0/user/houses',methods=['GET'])       #获取用户发布的房子和新发布房子
@pro_blue
def user_houses():
    if not g.user:
        return jsonify(errno=1,errmsg='用户未登陆')
    if request.method=='GET':
        user_house_list=House.query.filter(House.user_id==g.user.id).all()
        house_list=[]
        for i in user_house_list:
            house_list.append(i.to_basic_dict()) if i else ''
        return jsonify(data=house_list,errno=0,errmsg='ok')


@house_blue.route('/api/v1.0/houses',methods=['POST'])
@pro_blue
def add_house():
    if not g.user:
        return jsonify(errno=1,errmsg='用户未登陆')
    title = request.json.get('title')
    price = request.json.get('price')
    area_id = request.json.get('area_id')
    address = request.json.get('address')
    room_count = request.json.get('room_count')
    acreage = request.json.get('acreage')
    unit = request.json.get('unit')
    capacity = request.json.get('capacity')
    beds = request.json.get('beds')
    deposit = request.json.get('deposit')
    min_days = request.json.get('min_days')
    max_days = request.json.get('max_days')
    facility = request.json.get('facility')
    if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days,
                facility]):
        return jsonify(errno=1, errmsg='参数不全')
    if not (int(room_count) > 0 and int(acreage) > 0 and int(price) > 0 and int(capacity) > 0 and int(
            deposit) > 0 and int(min_days) > 0 and int(max_days)):
        return jsonify(errno=1, errmsg='参数格式错误')
    if int(min_days) > int(max_days):
        return jsonify(errno=1, errmsg='天数填写错误')
    house = House()
    house.user_id = g.user.id
    house.title = title
    house.price = int(price)
    house.area_id = int(area_id)
    house.address = address
    house.room_count = int(room_count)
    house.acreage = int(acreage)
    house.unit = unit
    house.capacity = int(capacity)
    house.beds = beds
    house.deposit = int(deposit)
    house.min_days = int(min_days)
    house.max_days = int(max_days)
    house.create_time = datetime.now()
    house.update_time = datetime.now()
    facility_list = []
    for i in facility:
        use_facility = Facility.query.filter(Facility.id == int(i)).first()
        facility_list.append(use_facility) if use_facility else ''
    house.facilities = facility_list
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=1, errmsg="数据库提交出错")
    data = {
        "house_id": house.id
    }
    return jsonify(errno=1, errmsg='ok', data=data)
@house_blue.route('/api/v1.0/areas',methods=['GET'])
@pro_blue
def areas():
    areas=Area.query.all()
    area_list=[]
    for i in areas:
        area_list.append(i.to_dict()) if i else ''
    return jsonify(errno=0,errmsg='ok',data=area_list)
@house_blue.route('/api/v1.0/houses/<int:house_id>/images',methods=['POST'])        #上传房子图片
@pro_blue
def house_images(house_id):
    if not g.user:
        return jsonify(errno=1, errmsg='用户未登陆')
    if not house_id:
        return jsonify(errno=1, errmsg='参数为空')
    house=House.query.filter(House.id==house_id).first()
    if not house:
        return jsonify(errno=1, errmsg='房子不存在')
    images=request.files.get('house_image')
    if not images:
        return jsonify(errno=1, errmsg='图片为空')
    try:
        images_name=image_storage(images.read())
    except Exception as e:
        current_app.logger.erron(e)
        return jsonify(errno=1, errmsg='上传失败')
    houseimage=HouseImage()
    houseimage.house_id=house_id
    houseimage.url=images_name
    house.images.append(houseimage)
    house.update_time=datetime.now()
    db.session.add(houseimage)
    db.session.commit()
    data={
        'url': "http://pkxzow2mg.bkt.clouddn.com/"+images_name
    }
    return jsonify(errno=0, errmsg='ok',data=data)
@house_blue.route('/api/v1.0/houses/<int:house_id>',methods=['GET'])        #展示房屋详情
def house_details(house_id):
    if not house_id:
        return jsonify(errno=1, errmsg='参数为空')
    house=House.query.filter(House.id==house_id).first()
    if not house:
        return jsonify(errno=1, errmsg='房子不存在')
    data={
        "house":house.to_full_dict()
    }
    return jsonify(errno=0, errmsg='ok',data=data)
@house_blue.route('/api/v1.0/houses/index',methods=['GET'])
def house_index():
    house_list=House.query.order_by(House.update_time.desc()).limit(10)
    house_dict_list=[]
    for i in house_list:
        house_dict_list.append(i.to_basic_dict()) if i else ''
    return jsonify(errno=0, errmsg='ok',data=house_dict_list)
@house_blue.route('/api/v1.0/houses',methods=['GET'])
def houses():
    aid=request.args.get('aid')
    sd=request.args.get('sd')
    ed=request.args.get('ed')
    sk=request.args.get('sk')
    p=int(request.args.get('p','1'))
    filters=[]
    oredr_list=[]
    if aid:
        filters.append(House.area_id==int(aid))
    if all([sd,ed]):
        sd_time=datetime.strptime(sd,'%Y-%m-%d')
        ed_time=datetime.strptime(ed,'%Y-%m-%d')
        de_time=ed_time-sd_time
        de_time=de_time.days
        filters.append(House.min_days<de_time)
    elif (not sd) and ed:
        ed_time = datetime.strptime(ed, '%Y-%m-%d')
        sd_time = time.localtime()
        de_time = ed_time - sd_time
        de_time = de_time.days
        filters.append(House.min_days < de_time)
    if sk:
        if sk=='booking':
            oredr_list.append(House.order_count.desc())
        elif sk=='price-inc':
            oredr_list.append(House.price.asc())
        elif sk=='price-des':
            oredr_list.append(House.price.desc())
    else:
        oredr_list.append(House.create_time.desc())
    house_list=House.query.filter(*filters).order_by(*oredr_list).paginate(int(p),5,False)
    total_page=house_list.pages
    items=house_list.items
    my_house_list=[]
    for i in items:
        my_house_list.append(i.to_basic_dict())
    data={
        'houses':my_house_list,
        'total_page':total_page
    }
    return jsonify(errno=0,errmsg='ok',data=data)
@house_blue.route('/<path:i>')
def indextext(i):
    if i != 'favicon.ico':
        i='html/'+i
    return current_app.send_static_file(i)
@house_blue.route('/')
def index():
    return current_app.send_static_file('html/index.html')




